package com.phonegap.breastmilk;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.phonegap.breastmilk.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Toast;

public class TabJournal extends Activity  {
	
	private AdapterJournal adapterJournal;
	private ListView listViewItem;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabjournal);
        SQLiteDatabase db = Connection.getInstance(this).getReadableDatabase();
        String from[] = new String [] {BreastmilkSQLiteHelper.ID,BreastmilkSQLiteHelper.DATE_BEGIN,BreastmilkSQLiteHelper.DATE_END,BreastmilkSQLiteHelper.BREAST_FED,BreastmilkSQLiteHelper.NOTES};
        Cursor cursor = db.query(
    			BreastmilkSQLiteHelper.DATABASE, 
    			from,
    			null, null, null, null, null);
        
        adapterJournal = AdapterJournal.getInstance(this, cursor, from);
        adapterJournal.changeCursor(cursor);
        listViewItem = (ListView)findViewById(R.id.listViewBreastfed);
	    listViewItem.setAdapter(adapterJournal);
	    int[] colors = {0, 0xFFFF0000, 0}; // red for the example
	    listViewItem.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
	    listViewItem.setDividerHeight(1);
	    
	    Button buttonClearAll = (Button)findViewById(R.id.buttonClearAll);
        buttonClearAll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				clearAll(v);
			}
		});
	    
	    listViewItem.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				// Get instance of Vibrator from current Context
				Vibrator v = (Vibrator) getSystemService(TabJournal.VIBRATOR_SERVICE);
				// Vibrate for 300 milliseconds
				v.vibrate(70);
				showDialogDeleteItem(parent, view, position, id);
				return false;
			}
		});
	    
	    listViewItem.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				showInformationItem(parent, view, position, id);
			}
	    	
		});
	    startManagingCursor(cursor);
 	   	db.close();
 	   	
 	   	Button buttonExport = (Button)findViewById(R.id.buttonExport);
 	   	buttonExport.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sendEmail(v);
			}
		});
	}
	
	public void sendEmail(View v) {
		File file = getCsvJournal(); 
		if ( file == null) {
			return;
		}
		Uri u1 = Uri.fromFile(file);
		
		// get time
    	final Calendar cal = Calendar.getInstance();
    	Pattern p = Pattern.compile("([\\w]+\\s[\\w]+\\s[0-9]+)\\s([0-9]+:[0-9]+:[0-9]+).*\\s([0-9]+)$");
    	Matcher m = p.matcher(cal.getTime().toString());
    	String fecha = "";
    	if (m.find()) {
			fecha = m.group(1) + ", " + m.group(3);
		}
    	
    	// Send email with attachment
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_EMAIL  , new String[]{""});
		intent.putExtra(Intent.EXTRA_SUBJECT, "Baby Feeding Journal");
		intent.putExtra(Intent.EXTRA_TEXT   , "My Baby Feeding Journal as of " + fecha);
		intent.putExtra(Intent.EXTRA_STREAM, u1);
		intent.setType("text/html");
		try {
		    startActivity(Intent.createChooser(intent, "Send mail..."));
		} catch (android.content.ActivityNotFoundException ex) {
		    Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		SQLiteDatabase db = Connection.getInstance(this).getReadableDatabase();
 	   	Cursor cursor = db.query(
    			BreastmilkSQLiteHelper.DATABASE, 
    			new String [] {BreastmilkSQLiteHelper.ID,BreastmilkSQLiteHelper.DATE_BEGIN,BreastmilkSQLiteHelper.DATE_END,BreastmilkSQLiteHelper.BREAST_FED,BreastmilkSQLiteHelper.NOTES}, 
    			null, null, null, null, null);
 	   	startManagingCursor(cursor);
 	   	adapterJournal.changeCursor(cursor);
 	   	db.close();
	}

	public File getCsvJournal() {
		// prepared CSV
		String columnString = "\"Start Time\",\"Stop Time\",\"Breast Fed\",\"Notes\"";
		SQLiteDatabase db = Connection.getInstance(this).getReadableDatabase();
		String from[] = new String [] {BreastmilkSQLiteHelper.ID,BreastmilkSQLiteHelper.DATE_BEGIN,BreastmilkSQLiteHelper.DATE_END,BreastmilkSQLiteHelper.BREAST_FED,BreastmilkSQLiteHelper.NOTES};
        Cursor cursor = db.query(
    			BreastmilkSQLiteHelper.DATABASE, 
    			from,
    			null, null, null, null, null);
        startManagingCursor(cursor);
        // get time
    	Pattern p = Pattern.compile("([\\w]+\\s[\\w]+\\s[0-9]+)\\s([0-9]+:[0-9]+:[0-9]+).*\\s([0-9]+)$");
        
        // Nos aseguramos de que existe al menos un registro
        String dataString = "";
        if (cursor.moveToFirst()) {
        	do {
        		Matcher m1 = p.matcher(cursor.getString(1));
            	String startDate = "";
            	if (m1.find()) {
            		startDate = m1.group(1) + ", " + m1.group(3) + " - " + m1.group(2);
        		}
            	Matcher m2 = p.matcher(cursor.getString(1));
            	String startEnd = "";
            	if (m2.find()) {
            		startEnd = m2.group(1) + ", " + m2.group(3) + " - " + m2.group(2);
        		}
        		dataString = "\"" + startDate + "\",\"" + startEnd + "\",\"" + cursor.getString(3) + "\",\"" + cursor.getString(4); 
        	} while(cursor.moveToNext());
        }
        
        db.close();
		String combinedString = columnString + "\n" + dataString;
		
		// create file
		File file = null;
		File root = Environment.getExternalStorageDirectory();
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			if (root.canWrite()) {
			    File dir = new File(root.getAbsolutePath() + "/PersonData");
			    dir.mkdirs();
			    file = new File(dir, "Baby Feeding Journal.csv");
			    FileOutputStream out = null;
			    try {
			        out = new FileOutputStream(file);
			    } catch (FileNotFoundException e) {
			    	e.printStackTrace();
			    }
			    
			    try {
			    	out.write(combinedString.getBytes());
			    } catch (IOException e) {
			    	e.printStackTrace();
			    }
			    
			    try {
			    	out.close();
			    } catch (IOException e) {
			    	e.printStackTrace();
			    }
			}
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Sorry sd card is not ready.")
			       .setCancelable(false)
			       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}
		
		return file;
	}
	
	/**
     * Delete all item
     * @param v
     */
    public void clearAll(View v) {
    	final Connection con = Connection.getInstance(this);
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage("Are you sure you want to erase all information permanently? It is highly recommended that you export  copy to save before proceeding.")
    	       .setCancelable(false)
    	       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       }).setPositiveButton("ERASE ALL", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   SQLiteDatabase db = con.getWritableDatabase();
    	        	   db.delete("Feeding_Diary", null, null);
    	        	   //AndroidTabsActivity.this.finish();
    	        	   Cursor cursor = db.query(
    	           			BreastmilkSQLiteHelper.DATABASE, 
    	           			new String [] {BreastmilkSQLiteHelper.ID,BreastmilkSQLiteHelper.DATE_BEGIN,BreastmilkSQLiteHelper.DATE_END,BreastmilkSQLiteHelper.BREAST_FED,BreastmilkSQLiteHelper.NOTES}, 
    	           			null, null, null, null, null);
    	        	   
    	        	   adapterJournal.changeCursor(cursor);
    	        	   startManagingCursor(cursor);
    	        	   db.close();
    	           }
    	       });
    	       
    	AlertDialog alert = builder.create();
    	try {
//    		alert.setView(v);
    		alert.show();
		} catch (Exception e) {
			Log.e("error alert", e.getMessage());
		}
    	
    }
    
    public void showDialogDeleteItem(AdapterView<?> parent, View view, int position, final long idItem) {
    	final Connection con = Connection.getInstance(this);
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage("Are you sure you want to erase this information permanently?")
    	       .setCancelable(false)
    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       }).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   SQLiteDatabase db = con.getWritableDatabase();
    	        	   db.delete("Feeding_Diary", "_id = "+idItem, null);
    	        	   //AndroidTabsActivity.this.finish();
    	        	   Cursor cursor = db.query(
    	           			BreastmilkSQLiteHelper.DATABASE, 
    	           			new String [] {BreastmilkSQLiteHelper.ID,BreastmilkSQLiteHelper.DATE_BEGIN,BreastmilkSQLiteHelper.DATE_END,BreastmilkSQLiteHelper.BREAST_FED,BreastmilkSQLiteHelper.NOTES}, 
    	           			null, null, null, null, null);
    	        	   adapterJournal.changeCursor(cursor);
    	        	   startManagingCursor(cursor);
    	        	   db.close();
    	           }
    	       });
    	       
    	AlertDialog alert = builder.create();
    	alert.show();
    }
    
    public void showInformationItem(AdapterView<?> parent, View view, int position, long id) {
        Bundle bundle = new Bundle();
        bundle.putInt("ID", (int) id);
//        intent.putExtras(bundle);
//        TabJournal.group.replaceContentView("ShowInformation", intent,  Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	/** Display Custom Dialog */
		CustomizeDialog customizeDialog = new CustomizeDialog(this, bundle);
		customizeDialog.show();
    }
    
    
	
}
